package com.dhcc.sdc.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.ICdcBsEmrStructService;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.components.httpClient.HttpClientServiceFactory;
import com.dhcc.core.components.httpClient.model.ServiceType;
import com.dhcc.core.components.httpClient.model.exception.ServiceImportException;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.core.modules.system.dao.UserMapper;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sdc.api.dao.SdsToolSdkMapper;
import com.dhcc.sdc.api.dto.DiagnosDataDto;
import com.dhcc.sdc.api.dto.DiagnosisDto;
import com.dhcc.sdc.api.function.IntheCheck;
import com.dhcc.sdc.api.service.ISdsToolService;
import com.dhcc.sdc.base.dao.SdcBaseAssessmenentryMapper;
import com.dhcc.sdc.base.dao.SdcBaseAssessmenitemMapper;
import com.dhcc.sdc.base.dao.SdcBaseAssessmentMapper;
import com.dhcc.sdc.base.entity.ContraindicationEntity;
import com.dhcc.sdc.base.entity.ContraindicationItemEntity;
import com.dhcc.sdc.base.entity.SdcBaseAssessmenentryEntity;
import com.dhcc.sdc.base.entity.SdcBaseAssessmentEntity;
import com.dhcc.sdc.base.service.IContraindicationItemService;
import com.dhcc.sdc.base.service.IContraindicationService;
import com.dhcc.sdc.busi.dao.*;
import com.dhcc.sdc.busi.entity.*;
import com.dhcc.sdc.busi.service.*;
import com.dhcc.sdc.cdss.dao.*;
import com.dhcc.sdc.cdss.dto.ArgumentData;
import com.dhcc.sdc.cdss.dto.GroupInfo;
import com.dhcc.sdc.cdss.entity.*;
import com.dhcc.sdc.cdss.service.ICdssApiService;
import com.dhcc.sdc.ws.SdsIntheCaseService.SdsIntheCaseServiceLocator;
import com.dhcc.sdc.ws.SdsIntheCaseService.SdsIntheCaseServiceSoap;
import com.dhcc.sds.base.cache.qcentity.QcEntityCache;
import com.dhcc.sds.base.dao.SdsFunctionMapper;
import com.dhcc.sds.base.dao.SdsQcfitemDicMapper;
import com.dhcc.sds.base.entity.*;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsExpressService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.dao.SdsQcfitemExecresultMapper;
import com.dhcc.sds.standard.dao.SdsStandRuleBaseMapper;
import com.dhcc.sds.standard.entity.SdsStandRuleBaseEntity;
import com.dhcc.sds.standard.service.ISdsStandRuleBaseService;
import com.dhcc.sds.standard.service.IsdsStandRuleCalService;
import com.dhcc.sds.ws.AddVteOrder.AddVteOrderWebServiceLocator;
import com.dhcc.sds.ws.AddVteOrder.AddVteOrderWebServiceSoap;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.xml.rpc.ServiceException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version 1.0 DHCC
 * @Description: 描述
 * @Project Name:
 * @Package Name:
 * @File Name:
 * @author:sunyingjie
 * @date:
 * @Copyright: (c) DHCC All rights reserved.
 */
@Service("sdsToolService")
public class SdsToolSdkServiceImpl implements ISdsToolService {

    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;
    @Autowired
    private ISdsExpressService sdsExpressService;
    @Autowired
    private ICdcEpisodeService cdcEpisodeService;
    @Autowired
    private ISdcBusiQcMrlistService sdcBusiQcMrlistService;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private ISdcBusiQcMrlislogService sdcBusiQcMrlislogService;
    @Autowired
    private SdsFunctionMapper sdsFunctionMapper;
    @Autowired
    private SdsToolSdkMapper sdsToolSdkMapper;
    @Autowired
    private SdsQcfitemDicMapper sdsQcfitemDicMapper;
    @Autowired
    private SdsQcfitemExecresultMapper sdsQcfitemExecresultMapper;
    @Autowired
    private SdcBusiEvaluationItemMapper sdcBusiEvaluationItemMapper;
    @Autowired
    private CdcOrdmastMapper cdcOrdmastMapper;
    @Autowired
    private ICdssApiService cdssApiService;
    @Autowired
    private SdcCdssItemMapper sdcCdssItemMapper;
    @Autowired
    private SdcCdssItemMatchMapper sdcCdssItemMatchMapper;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private SdcCdssItemResultMapper sdcCdssItemResultMapper;
    @Autowired
    private IIPQCService iipqcService;
    @Autowired
    private IContraindicationService contraindicationService;
    @Autowired
    private IContraindicationItemService contraindicationItemService;
    @Resource
    private SdcBusiContraindicationDtlMapper sdcBusiContraindicationDtlMapper;
    @Resource
    private SdcBusiContraindicationHisMapper sdcBusiContraindicationHisMapper;
    @Resource
    private SdcBusiContraindicationMapper sdcBusiContraindicationMapper;
    @Autowired
    private ICdcBsEmrStructService cdcBsEmrStructService;
    @Resource
    private CdcEmrMapper cdcEmrMapper;
    @Resource
    private SdcBaseAssessmentMapper sdcBaseAssessmentMapper;
    @Resource
    private SdcBaseAssessmenitemMapper sdcBaseAssessmenitemMapper;
    @Resource
    private SdcBusiEvaluationMapper sdcBusiEvaluationMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SdcBusiEvaluationHisMapper sdcBusiEvaluationHisMapper;
    @Resource
    private CdcOrdgroupMapper cdcOrdgroupMapper;
    @Resource
    private CdcOrdgroupEntryMapper cdcOrdgroupEntryMapper;

    @Resource
    private SdcCdssItemStageDicMapper sdcCdssItemStageDicMapper;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ICdcDataService cdcDataService;
    @Resource
    private CdcDiagnosisMapper cdcDiagnosisMapper;
    @Autowired
    private SdcBusiQcTriggeredMapper sdcBusiQcTriggeredMapper;
    @Autowired
    IsdsStandRuleCalService isdsStandRuleCalService;
    @Autowired
    private ISdsStandRuleBaseService iSdsStandRuleBaseService;
    @Autowired
    private SdcBaseAssessmenentryMapper sdcBaseAssessmenentryMapper;

    @Value("${sys.dhcHisCacheIp}")
    private String dhcHisCacheIp;  //获取his发布的接口地址 127.0.0.1
    @Value("${sys.dhcHisCachePath}")
    private String dhcHisCachePath; //获取his接口路径  imedical/web   dthealth/web
    @Value("${sys.dhcHisInterfaceHead}")
    private boolean dhcHisInterfaceHead; //东华HIS对外接口是否有head验证 true 有 false无
    @Value("${sys.hospitalName}")
    private String hospitalName; //医院名称

    /**
     * 患者就诊信息
     **/
    public static final int type_base = 0;
    /*入组提示*/
    public static final int type_in = 1;
    /*出组提示*/
    public static final int type_out = 2;
    /*诊疗辅助*/
    public static final int type_cdss = 3;
    /*质控提醒*/
    public static final int type_qc = 4;
    /*禁忌*/
    public static final int type_ci = 5;
    /*病种变更*/
    public static final int type_change = 6;
    /*病种信息*/
    public static final int type_entity = 9;
    /*手动出组*/
    public static final int type_operate = 7;
    /*病种已禁用*/
    public static final int type_notactive = 8;
    /*质控条目弹框*/
    public static final int type_isBox_alert = 13;

    protected static final Logger logger = LoggerFactory.getLogger(SdsToolSdkServiceImpl.class);

    /**
     * @param params
     * @return
     * @Description: 分析临床交互数据
     * @Title: analysisClinicData
     * @author: sunyingjie
     * @date: 2021年07月16日15:08:52
     */
    public JSONArray analysisClinicData(Map<String, Object> params) {
        // 结果返回结构
        JSONArray jsonArray = new JSONArray();
        if (CommonUtil.isAllEmpty(params)) {
            return jsonArray;
        }
        String episodeId = String.valueOf(params.get("episodeId")); // 就诊号
        String pageSource = String.valueOf(params.get("pageSource")); // 数据类型（来源）
        // 查询数据中心的对应的就诊id
        Map map = new HashMap();
        map.put("xcode", episodeId);
        List<CdcEpisodeEntity> cdcEpisodes = cdcEpisodeService.list(map);
        if (cdcEpisodes.size() == 0) {
            return jsonArray;
        }
        CdcEpisodeEntity cdcEpisode = cdcEpisodes.get(0);
        String patientId = cdcEpisode.getId().toString();
        params.put("patientId", patientId);

        // NLP解析电子病历、检查
        String dhcaiUrl = CdcConfigCache.me().getValueByKey("SDS", "SDAnalysisServer");
        if (!StringUtils.isEmpty(dhcaiUrl)) {
            List<CdcEmrEntity> emrList = cdcEmrMapper.selectList(new EntityWrapper<CdcEmrEntity>().eq("episode_id", patientId).gt("emr_date", DateUtil.getDay()));
            cdcBsEmrStructService.emrStructByNLP(dhcaiUrl, emrList);
        }

        // 判断是否手动出组
        Wrapper<SdcBusiQcMrlistEntity> outWpr = new EntityWrapper<>();
        outWpr.eq("episode_id", patientId).eq("state", "O")
                .eq("group_status", "ActivePart").orderDesc(Arrays.asList(new String[]{"in_date","in_time"}));
        List<SdcBusiQcMrlistEntity> outList = sdcBusiQcMrlistService.selectList(outWpr);
        if (outList.size() == 0) {
            // 判断病例是否已经入组
            Wrapper<SdcBusiQcMrlistEntity> mrWpr = new EntityWrapper<>();
            mrWpr.eq("episode_id", patientId).ne("state", "O");
            SdcBusiQcMrlistEntity mrList = sdcBusiQcMrlistService.selectOne(mrWpr);
            // 没有入组
            SdsQcentityEntity inthe = new SdsQcentityEntity();
            if (mrList == null) {
                // 入组判定
                try {
                    inthe = this.enrollment(params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (CommonUtil.isNotEmpty(inthe.getId())) {
                /*// 新入组患者, 需医生确认入组
                JSONObject inoutInfo = new JSONObject();
                String inMsg  = "当前患者符合病种「%s」的入组条件, 是否进入该病种的过程质控？";
                inMsg = String.format(inMsg, inthe.getBtDesc());
                inoutInfo.put("intOutMsg", inMsg);
                inoutInfo.put("curMrListId", null);
                inoutInfo.put("oldDis", null);
                inoutInfo.put("newDisId", inthe.getId());
                inoutInfo.put("type", type_in);
                jsonArray.add(inoutInfo);
                return  jsonArray;*/
                    Map hisMap = new HashMap();
                    hisMap.put("episodeId", params.get("episodeId"));
                    hisMap.put("diseaseType", inthe.getBtDesc());
                    hisMap.put("modifyUser", params.get("userCode"));
                    hisMap.put("isActive", "1");
                    this.pushIntheInfo2His(hisMap);
                }
            } else {
                try {
                    // 针对当前在组病种重新判定
                    inthe = this.enrollment(params, mrList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 原来在组，后续判定出组的情况
                if (CommonUtil.isEmpty(inthe.getId())) {
                    JSONObject inoutInfo = new JSONObject();
                    String outMsg = "当前患者因诊断/医嘱变更等原因，系统判断已退出当前质控病种「%s」，请知悉。";
                    SdsQcentityEntity outEntity = QcEntityCache.me().getQcEntityById(mrList.getEntityId());
                    outMsg = String.format(outMsg, outEntity.getBtDesc());
                    inoutInfo.put("intOutMsg", outMsg);
                    inoutInfo.put("curMrListId", mrList.getId());
                    inoutInfo.put("oldDisId", outEntity.getId());
                    inoutInfo.put("newDisId", null);
                    inoutInfo.put("type", type_out);
                    jsonArray.add(inoutInfo);
                    return jsonArray;
                } else {
                    // 新入组病种和原来病种不一致
                    if (!Objects.equals(inthe.getId(), mrList.getEntityId())) {
                        JSONObject inoutInfo = new JSONObject();
                        String changeMsg = "当前患者因诊断/医嘱变更等原因，系统判断退出当前质控病种「%s」且调整为新病种「%s」，请知悉。";
                        SdsQcentityEntity oldEntity = QcEntityCache.me().getQcEntityById(mrList.getEntityId());
                        changeMsg = String.format(changeMsg, oldEntity.getBtDesc(), inthe.getBtDesc());
                        inoutInfo.put("intOutMsg", changeMsg);
                        inoutInfo.put("curMrListId", mrList.getId());
                        inoutInfo.put("oldDisId", oldEntity.getId());
                        inoutInfo.put("newDisId", inthe.getId());
                        inoutInfo.put("type", type_change);
                        jsonArray.add(inoutInfo);
                        return jsonArray;
                    }
                }
            }
            // 如果确定入组
            if (CommonUtil.isNotEmpty(inthe.getId())) {
                //判断病种是否启用
                if(0 == inthe.getPlanActive()){
                    JSONObject inoutInfo = new JSONObject();
                    //SdsQcentityEntity outEntity = QcEntityCache.me().getQcEntityById(outList.get(0).getEntityId());
                    inoutInfo.put("curMrListId", null);
                    inoutInfo.put("oldDisId", null);
                    inoutInfo.put("newDisId", null);
                    inoutInfo.put("type", type_notactive);
                    jsonArray.add(inoutInfo);
                    return jsonArray;
                }else{
                    JSONObject data = new JSONObject();
                    data.put("type", type_entity);
                    data.put("entityId", inthe.getId());
                    data.put("entityDesc", inthe.getBtDesc());
                    jsonArray.add(data);
                    // 获取患者全量信息
                    ArgumentData argumentData = cdssApiService.createArgumentData(patientId);
                    GroupInfo groupInfo = new GroupInfo();
                    groupInfo.setName("SDS");
                    groupInfo.setSingleDisease(CommonUtil.isNotEmpty(inthe.getCdssName())?inthe.getCdssName():inthe.getBtDesc());
                    groupInfo.setSingleDiseaseId(inthe.getId().toString());
                    argumentData.setGroupInfo(groupInfo);
                    // 调用cdss接口，返回请求类型数据
                    JSONArray cdssResult = new JSONArray();
                    // 一次请求全部数据
                    String typeStr = ArgumentData.ParamType.RecommendLabExam + "," + ArgumentData.ParamType.AssistTreat + "," + ArgumentData.ParamType.RecommendNursing + "," + ArgumentData.ParamType.RecommendAssess;
                    argumentData.setType(typeStr);
                    JSONObject cdssInfo = cdssApiService.cdssData(argumentData);
                    cdssResult.addAll(cdssInfo.getJSONArray("cdssInfo"));
                    // 过滤禁用的诊疗方案
                    JSONArray filterForbiddenItem = cdssApiService.filterForbiddenItem(patientId, inthe.getId(), cdssResult);
                    // 过滤已完成的诊疗措施
                    JSONArray filterResult = cdssApiService.filterResult(patientId, inthe.getId(), filterForbiddenItem);
                    cdssInfo.put("cdssInfo", filterResult);
                    cdssInfo.put("type", type_cdss);
                    cdssInfo.put("status", cdssInfo.get("cdssStatus"));
                    jsonArray.add(cdssInfo);
                    // 质控条目
                    JSONArray ipqcResult = iipqcService.QCInfo(Long.valueOf(patientId), inthe.getId());

                    //判断质控条目是否弹框  配置的弹框频率
                    String qcBoxConfig = CdcConfigCache.me().getValueByKey("SDS", "QCBox");
                    List<String> needQcBox =iipqcService.QCBoxInfo(Long.valueOf(patientId), inthe.getId());
                    JSONObject qcIsBox = new JSONObject();
                    qcIsBox.put("qcBoxConfig", qcBoxConfig);
                    qcIsBox.put("needQcBox", needQcBox);
                    qcIsBox.put("entityDesc", inthe.getBtDesc());
                    qcIsBox.put("type", type_isBox_alert);
                    jsonArray.add(qcIsBox);

                    //删除禁用的质控条目触发记录
                    iipqcService.deleteForbiddenQcTriggered(Long.valueOf(patientId), inthe.getId());
                    JSONObject ipqcInfo = new JSONObject();
                    ipqcInfo.put("ipqcInfo", ipqcResult);
                    ipqcInfo.put("type", type_qc);
                    jsonArray.add(ipqcInfo);
                    // 禁忌症信息  修改为诊疗方案关联禁忌，去掉原页签
//                    JSONArray ciResult = contraindicationService.CIInfo(Long.valueOf(patientId), inthe.getId());
//                    JSONObject ciInfo = new JSONObject();
//                    ciInfo.put("ciInfo", ciResult);
//                    ciInfo.put("type", type_ci);
//                    jsonArray.add(ciInfo);
                    // 患者信息
                    JSONObject patientInfo = new JSONObject();
                    patientInfo.put("name", cdcEpisode.getName());
                    patientInfo.put("mrNo", cdcEpisode.getMrNum());
                    patientInfo.put("isDeath", cdcEpisode.getIsDeath());
                    patientInfo.put("type", type_base);
                    jsonArray.add(patientInfo);
                }
            }
        }
        else{
                JSONObject inoutInfo = new JSONObject();
                SdsQcentityEntity outEntity = QcEntityCache.me().getQcEntityById(outList.get(0).getEntityId());
                inoutInfo.put("curMrListId", outList.get(0).getId());
                inoutInfo.put("oldDisId", outEntity.getId());
                inoutInfo.put("newDisId", null);
                inoutInfo.put("type", type_operate);
                jsonArray.add(inoutInfo);
                return jsonArray;
            }
        return jsonArray;
    }

    public JSONArray analysisClinicData2(String episodeId, String userName){
        // 结果返回结构
        JSONArray jsonArray = new JSONArray();
        Map<String, Object> params = new HashMap<>();
        // 查询数据中心的对应的就诊id
        Map map = new HashMap();
        map.put("xcode", episodeId);
        List<CdcEpisodeEntity> cdcEpisodes = cdcEpisodeService.list(map);
        if (cdcEpisodes.size() == 0) {
            return jsonArray;
        }
        CdcEpisodeEntity cdcEpisode = cdcEpisodes.get(0);
        String patientId = cdcEpisode.getId().toString();
        params.put("patientId", patientId);

        // 判断是否手动出组
        Wrapper<SdcBusiQcMrlistEntity> outWpr = new EntityWrapper<>();
        outWpr.eq("episode_id", patientId).eq("state", "O")
                .eq("group_status", "ActivePart").orderDesc(Arrays.asList(new String[]{"in_date","in_time"}));
        List<SdcBusiQcMrlistEntity> outList = sdcBusiQcMrlistService.selectList(outWpr);
        if (outList.size() == 0){
            // 判断病例是否已经入组
            Wrapper<SdcBusiQcMrlistEntity> mrWpr = new EntityWrapper<>();
            mrWpr.eq("episode_id", patientId).ne("state", "O");
            SdcBusiQcMrlistEntity mrList = sdcBusiQcMrlistService.selectOne(mrWpr);
            // 没有入组
            SdsQcentityEntity inthe = new SdsQcentityEntity();
            if (mrList == null) {
                // 入组判定
                try {
                    inthe = this.enrollment(params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (CommonUtil.isNotEmpty(inthe.getId())){
                    Map hisMap = new HashMap();
                    hisMap.put("episodeId", episodeId);
                    hisMap.put("diseaseType", inthe.getBtDesc());
                    hisMap.put("modifyUser", userName);
                    hisMap.put("isActive", "1");
                    this.pushIntheInfo2His(hisMap);
                }
            }else {
                try {
                    // 针对当前在组病种重新判定
                    inthe = this.enrollment(params, mrList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 原来在组，后续判定出组的情况
                if (CommonUtil.isEmpty(inthe.getId())) {
                    JSONObject inoutInfo = new JSONObject();
                    String outMsg = "当前患者因诊断/医嘱变更等原因，系统判断已退出当前质控病种「%s」，请知悉。";
                    SdsQcentityEntity outEntity = QcEntityCache.me().getQcEntityById(mrList.getEntityId());
                    outMsg = String.format(outMsg, outEntity.getBtDesc());
                    inoutInfo.put("intOutMsg", outMsg);
                    inoutInfo.put("curMrListId", mrList.getId());
                    inoutInfo.put("oldDisId", outEntity.getId());
                    inoutInfo.put("newDisId", null);
                    inoutInfo.put("type", type_out);
                    jsonArray.add(inoutInfo);
                    return jsonArray;
                } else {
                    // 新入组病种和原来病种不一致
                    if (!Objects.equals(inthe.getId(), mrList.getEntityId())) {
                        JSONObject inoutInfo = new JSONObject();
                        String changeMsg = "当前患者因诊断/医嘱变更等原因，系统判断退出当前质控病种「%s」且调整为新病种「%s」，请知悉。";
                        SdsQcentityEntity oldEntity = QcEntityCache.me().getQcEntityById(mrList.getEntityId());
                        changeMsg = String.format(changeMsg, oldEntity.getBtDesc(), inthe.getBtDesc());
                        inoutInfo.put("intOutMsg", changeMsg);
                        inoutInfo.put("curMrListId", mrList.getId());
                        inoutInfo.put("oldDisId", oldEntity.getId());
                        inoutInfo.put("newDisId", inthe.getId());
                        inoutInfo.put("type", type_change);
                        jsonArray.add(inoutInfo);
                        return jsonArray;
                    }
                }
            }
            // 如果确定入组
            if (CommonUtil.isNotEmpty(inthe.getId())){
                JSONObject data = new JSONObject();
                data.put("type", type_entity);
                data.put("entityId", inthe.getId());
                data.put("entityDesc", inthe.getBtDesc());
                jsonArray.add(data);
                // 获取患者全量信息
                ArgumentData argumentData = cdssApiService.createArgumentData(patientId);
                GroupInfo groupInfo = new GroupInfo();
                groupInfo.setName("SDS");
                groupInfo.setSingleDisease(inthe.getBtDesc());
                groupInfo.setSingleDiseaseId(inthe.getId().toString());
                argumentData.setGroupInfo(groupInfo);
                // 调用cdss接口，返回请求类型数据
                JSONArray cdssResult = new JSONArray();
                // 一次请求全部数据
                String typeStr = ArgumentData.ParamType.RecommendLabExam + "," + ArgumentData.ParamType.AssistTreat + "," + ArgumentData.ParamType.RecommendNursing + "," + ArgumentData.ParamType.RecommendAssess;
                argumentData.setType(typeStr);
                JSONObject cdssInfo = cdssApiService.cdssData(argumentData);
                cdssResult.addAll(cdssInfo.getJSONArray("cdssInfo"));
                // 过滤已完成的诊疗措施
                JSONArray filterResult = cdssApiService.filterResult(patientId, inthe.getId(), cdssResult);
                cdssInfo.put("cdssInfo", filterResult);
                cdssInfo.put("type", type_cdss);
                cdssInfo.put("status", cdssInfo.get("cdssStatus"));
                jsonArray.add(cdssInfo);
                // 质控条目
                JSONArray ipqcResult = iipqcService.QCInfo(Long.valueOf(patientId), inthe.getId());
                JSONObject ipqcInfo = new JSONObject();
                ipqcInfo.put("ipqcInfo", ipqcResult);
                ipqcInfo.put("type", type_qc);
                jsonArray.add(ipqcInfo);
                // 禁忌症信息
                JSONArray ciResult = contraindicationService.CIInfo(Long.valueOf(patientId), inthe.getId());
                JSONObject ciInfo = new JSONObject();
                ciInfo.put("ciInfo", ciResult);
                ciInfo.put("type", type_ci);
                jsonArray.add(ciInfo);
                // 患者信息
                JSONObject patientInfo = new JSONObject();
                patientInfo.put("name", cdcEpisode.getName());
                patientInfo.put("mrNo", cdcEpisode.getMrNum());
                patientInfo.put("isDeath", cdcEpisode.getIsDeath());
                patientInfo.put("type", type_base);
                jsonArray.add(patientInfo);
            }
        }else {
            JSONObject inoutInfo = new JSONObject();
            SdsQcentityEntity outEntity = QcEntityCache.me().getQcEntityById(outList.get(0).getEntityId());
            inoutInfo.put("curMrListId", outList.get(0).getId());
            inoutInfo.put("oldDisId", outEntity.getId());
            inoutInfo.put("newDisId", null);
            inoutInfo.put("type", type_operate);
            jsonArray.add(inoutInfo);
            return jsonArray;
        }

        return jsonArray;
    }

    /**
     * 入组判定
     *
     * @param params 临床参数-诊断信息
     * @return 入组病种
     */
    private SdsQcentityEntity enrollment(Map<String, Object> params) throws Exception {
        SdsQcentityEntity inthe = new SdsQcentityEntity();

        Long episodeId = Long.valueOf(params.get("patientId").toString()); // 就诊号
        ///如果患者已经存在有效的单病种表单，则退出入组判断
        Wrapper<SdcBusiQcMrlistEntity> mrWpr = new EntityWrapper<>();
        mrWpr.eq("episode_id", episodeId).ne("state", "O");
        SdcBusiQcMrlistEntity mrList = sdcBusiQcMrlistService.selectOne(mrWpr);
        if (CommonUtil.isNotEmpty(mrList)) {
            inthe = QcEntityCache.me().getQcEntityById(mrList.getEntityId());
            return inthe;
        }

        //通过就诊id获取就诊对象
        CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeService.selectById(episodeId);

        //遍历已经开展的质控病种
        Long mrListID = null;

        Long entityTypeId = sdsCommonService.getDictId("QcentityType","Up");
        Wrapper<SdsQcentityEntity> wpr = new EntityWrapper<>();
        wpr.ne("is_active", 0).eq("entity_type_id",entityTypeId).orderBy("ind_no"); // 非作废病种且按照排序码排序
        List<SdsQcentityEntity> qcentityEntities = sdsQcentityService.selectList(wpr);
        a:
        for (SdsQcentityEntity sdsQcentityEntity : qcentityEntities) {
            if (!StringUtils.isEmpty(mrListID) || CommonUtil.isNotEmpty(inthe.getId())) {
                //已入病种，退出判断
                break a;
            }

            //防止排除的病种再次筛查
            Wrapper<SdcBusiQcMrlistEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("episode_id", episodeId)
                    .eq("entity_id", sdsQcentityEntity.getId())
                    .eq("group_status", "ActivePart") // 手动排除标识
                    .eq("state", "O");
            List<SdcBusiQcMrlistEntity> list = sdcBusiQcMrlistService.selectList(wrapper);
            if (!list.isEmpty()) {
                continue;
            }
            Map<String, Object> map2 = new HashMap<>();
            map2.put("entityId", sdsQcentityEntity.getId());
            List<SdsQcentityRuleEntity> qcentityRuleEntities = sdsQcentityRuleService.list(map2);
            //准入规则
            List<SdsQcentityRuleEntity> admits = new ArrayList<>();
            //排除规则
            List<SdsQcentityRuleEntity> exclude = new ArrayList<>();
            for (SdsQcentityRuleEntity sdsQcentityRuleEntity : qcentityRuleEntities) {
                if (!Objects.equals(1, sdsQcentityRuleEntity.getIsActive())) {
                    continue;
                }
                if (Objects.equals("1", sdsQcentityRuleEntity.getRuleType())) {
                    admits.add(sdsQcentityRuleEntity);
                } else {
                    exclude.add(sdsQcentityRuleEntity);
                }
            }
            //有准入配置，才进行入组判断
            String ret = "";
            String ruleId = "";
            if (!admits.isEmpty()) {
                Date nowDate = new Date();
                //Param2:判断且伴为同一组的准入规则，排序相同的为同一组
                //String param2 = sdsQcentityRuleEntity.getParam2();
                //按Param2进行分组
                Map<String, List<SdsQcentityRuleEntity>> collect = admits.stream().collect(Collectors.groupingBy(p -> p.getParam2() == null ? "" : p.getParam2(), Collectors.toList()));
                b:
                for (String param2 : collect.keySet()) {
                    List<SdsQcentityRuleEntity> sdsQcentityRuleEntities = collect.get(param2);
                    //每一组ruleId重置
                    ruleId = "";
                    for (SdsQcentityRuleEntity sdsQcentityRuleEntity : sdsQcentityRuleEntities) {
                        ret = "N";
                        SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
                        if (!StringUtils.isEmpty(sdsExpressEntity)) {
                            Class c = Class.forName("com.dhcc.sdc.api.function.IntheCheck");
                            IntheCheck intheCheckSrv = (IntheCheck) c.newInstance();
                            Method method = c.getMethod(sdsExpressEntity.getExpress(), Long.class, String.class);
                            ret = (String) method.invoke(intheCheckSrv, episodeId, sdsQcentityRuleEntity.getParam());
                            if (!Objects.equals("Y", ret)) {
                                continue b;
                            } else {
                                //记录ruleId
                                ruleId += sdsQcentityRuleEntity.getId() + ",";
                            }
                        }
                    }
                    if (Objects.equals("Y", ret)) {
                        //多个准入，并行满足一个跳出
                        break b;
                    }
                }
                DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
                definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                TransactionStatus transactionStatus = platformTransactionManager.getTransaction(definition);
                try {
                    if (Objects.equals("Y", ret)) {
                        //如果满足第一准入条件，直接进入单病种列表
                        SdcBusiQcMrlistEntity sdsQcincaseEntity = new SdcBusiQcMrlistEntity();
                        sdsQcincaseEntity.setEpisodeId(episodeId);
                        sdsQcincaseEntity.setEntityId(sdsQcentityEntity.getId());
                        sdsQcincaseEntity.setInUserId(String.valueOf(cdcEpisodeEntity.getAdmDoctorId()));
                        sdsQcincaseEntity.setInLocId(String.valueOf(cdcEpisodeEntity.getAdmLocId()));
                        sdsQcincaseEntity.setInWardId(String.valueOf(cdcEpisodeEntity.getAdmWardId()));
                        sdsQcincaseEntity.setInDate(nowDate);
                        sdsQcincaseEntity.setInTime(nowDate);
                        sdsQcincaseEntity.setState("I");
                        sdsQcincaseEntity.setGroupStatus("SysRec");
                        Wrapper<SdcBusiQcMrlistEntity> inListWrapper = new EntityWrapper<>();
                        inListWrapper.eq("episode_id",episodeId);
                        inListWrapper.eq("entity_id",sdsQcentityEntity.getId());
                        inListWrapper.eq("state","O");
                        inListWrapper.eq("group_status","SysRec");
                        List<SdcBusiQcMrlistEntity> oldList = sdcBusiQcMrlistService.selectList(inListWrapper);
                        boolean insert=false;
                        if(CommonUtil.isEmpty(oldList)){
                            insert = sdcBusiQcMrlistService.insert(sdsQcincaseEntity);
                        }else{
                            SdcBusiQcMrlistEntity inQc = oldList.get(0);
                            inQc.setInUserId(String.valueOf(cdcEpisodeEntity.getAdmDoctorId()));
                            inQc.setInLocId(String.valueOf(cdcEpisodeEntity.getAdmLocId()));
                            inQc.setInWardId(String.valueOf(cdcEpisodeEntity.getAdmWardId()));
                            inQc.setInDate(nowDate);
                            inQc.setInTime(nowDate);
                            inQc.setState("I");
                            sdcBusiQcMrlistService.updateById(inQc);
                            sdsQcincaseEntity = inQc;
                        }

                        if (insert) {
                            //增加病历状态记录
                            SdcBusiQcMrlislogEntity sdsQcincaseOperlogEntity = new SdcBusiQcMrlislogEntity();
                            sdsQcincaseOperlogEntity.setMrlistId(sdsQcincaseEntity.getId());
                            sdsQcincaseOperlogEntity.setOperState("I");
                            sdsQcincaseOperlogEntity.setOperUser("系统");
                            sdsQcincaseOperlogEntity.setOperDate(nowDate);
                            sdsQcincaseOperlogEntity.setOperReason(ruleId);
                            boolean insert1 = sdcBusiQcMrlislogService.insert(sdsQcincaseOperlogEntity);
                            if (insert1) {
                                mrListID = sdsQcincaseEntity.getId();
                            }
                        }
                        inthe = sdsQcentityEntity;

                        String ruleIDStr = "";
                        if (!exclude.isEmpty()) {
                            //对于符合准入条件，且有排除配置的病例，做自动排除判断
                            for (SdsQcentityRuleEntity sdsQcentityRuleEntity : exclude) {
                                SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
                                if (!StringUtils.isEmpty(sdsExpressEntity)) {
                                    Class<?> aClass = Class.forName("com.dhcc.sdc.api.function.IntheCheck");
                                    IntheCheck intheCheckSrv = (IntheCheck) aClass.newInstance();
                                    Method method = aClass.getMethod(sdsExpressEntity.getExpress(), Long.class, String.class);
                                    ret = (String) method.invoke(intheCheckSrv, episodeId, sdsQcentityRuleEntity.getParam());

                                    if (Objects.equals("Y", ret)) {
                                        ruleIDStr = sdsQcentityRuleEntity.getId() + "";
                                        break;
                                    }
                                }
                            }
                            if (!StringUtils.isEmpty(ruleIDStr)) {
                                sdsQcincaseEntity.setOutDate(nowDate);
                                sdsQcincaseEntity.setOutTime(nowDate);
                                sdsQcincaseEntity.setState("O");
                                boolean b = sdcBusiQcMrlistService.updateById(sdsQcincaseEntity);
                                if (b && insert) {
                                    SdcBusiQcMrlislogEntity sdsQcincaseOperlogEntity = new SdcBusiQcMrlislogEntity();
                                    sdsQcincaseOperlogEntity.setMrlistId(sdsQcincaseEntity.getId());
                                    sdsQcincaseOperlogEntity.setOperState("O");
                                    sdsQcincaseOperlogEntity.setOperUser("系统");
                                    sdsQcincaseOperlogEntity.setOperDate(nowDate);
                                    sdsQcincaseOperlogEntity.setOperReason(ruleIDStr);
                                    boolean insert1 = sdcBusiQcMrlislogService.insert(sdsQcincaseOperlogEntity);
                                    if (insert1) {
                                        mrListID = null;
                                    }
                                }
                                inthe = new SdsQcentityEntity();
                            }
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    platformTransactionManager.rollback(transactionStatus);
                }
                platformTransactionManager.commit(transactionStatus);
            }
        }
        return inthe;
    }

    /**
     * 出组判定
     * 针对入组病种重新跑一遍入组、排除规则
     *
     * @param params 临床参数
     * @return 出组判定结果
     */
    private SdsQcentityEntity exclude(Map<String, Object> params, SdcBusiQcMrlistEntity sdcBusiQcMrlist) throws Exception {
        Long episodeId = Long.valueOf(params.get("episodeId").toString()); // 就诊号
        Long entityId = sdcBusiQcMrlist.getEntityId(); // 入组病种

        SdsQcentityEntity inthe = QcEntityCache.me().getQcEntityById(entityId);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("entityId", sdcBusiQcMrlist.getEntityId());
        List<SdsQcentityRuleEntity> qcentityRuleEntities = sdsQcentityRuleService.list(map2);
        //准入规则
        List<SdsQcentityRuleEntity> admits = new ArrayList<>();
        //排除规则
        List<SdsQcentityRuleEntity> exclude = new ArrayList<>();
        for (SdsQcentityRuleEntity sdsQcentityRuleEntity : qcentityRuleEntities) {
            if (!Objects.equals(1, sdsQcentityRuleEntity.getIsActive())) {
                continue;
            }
            if (Objects.equals("1", sdsQcentityRuleEntity.getRuleType())) {
                admits.add(sdsQcentityRuleEntity);
            } else {
                exclude.add(sdsQcentityRuleEntity);
            }
        }

        //有准入配置，才进行入组判断
        Date nowDate = new Date();
        String ret = "";
        String ruleId = "";
        if (!admits.isEmpty()) {
            //Param2:判断且伴为同一组的准入规则，排序相同的为同一组
            //String param2 = sdsQcentityRuleEntity.getParam2();
            //按Param2进行分组
            Map<String, List<SdsQcentityRuleEntity>> collect = admits.stream().collect(Collectors.groupingBy(p -> p.getParam2() == null ? "" : p.getParam2(), Collectors.toList()));
            b:
            for (String param2 : collect.keySet()) {
                List<SdsQcentityRuleEntity> sdsQcentityRuleEntities = collect.get(param2);
                //每一组ruleId重置
                ruleId = "";
                for (SdsQcentityRuleEntity sdsQcentityRuleEntity : sdsQcentityRuleEntities) {
                    ret = "N";
                    SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
                    if (!StringUtils.isEmpty(sdsExpressEntity)) {
                        Class c = Class.forName("com.dhcc.sdc.api.function.IntheCheck");
                        IntheCheck intheCheckSrv = (IntheCheck) c.newInstance();
                        Method method = c.getMethod(sdsExpressEntity.getExpress(), Long.class, String.class);
                        ret = (String) method.invoke(intheCheckSrv, episodeId, sdsQcentityRuleEntity.getParam());
                        if (!Objects.equals("Y", ret)) {
                            continue b;
                        } else {
                            //记录ruleId
                            ruleId += sdsQcentityRuleEntity.getId() + ",";
                        }
                    }
                }
                if (Objects.equals("Y", ret)) {
                    //多个准入，并行满足一个跳出
                    break b;
                }
            }
            DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
            definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            TransactionStatus transactionStatus = platformTransactionManager.getTransaction(definition);
            try {
                if (Objects.equals("Y", ret)) {
                    String ruleIDStr = "";
                    if (!exclude.isEmpty()) {
                        //对于符合准入条件，且有排除配置的病例，做自动排除判断
                        for (SdsQcentityRuleEntity sdsQcentityRuleEntity : exclude) {
                            SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
                            if (!StringUtils.isEmpty(sdsExpressEntity)) {
                                Class<?> aClass = Class.forName("com.dhcc.sdc.api.function.IntheCheck");
                                IntheCheck intheCheckSrv = (IntheCheck) aClass.newInstance();
                                Method method = aClass.getMethod(sdsExpressEntity.getExpress(), Long.class, String.class);
                                ret = (String) method.invoke(intheCheckSrv, episodeId, sdsQcentityRuleEntity.getParam());

                                if (Objects.equals("Y", ret)) {
                                    ruleIDStr = sdsQcentityRuleEntity.getId() + "";
                                    break;
                                }
                            }
                        }
                        if (!StringUtils.isEmpty(ruleIDStr)) {
                            sdcBusiQcMrlist.setOutDate(nowDate);
                            sdcBusiQcMrlist.setOutTime(nowDate);
                            sdcBusiQcMrlist.setState("O");
                            boolean b = sdcBusiQcMrlistService.updateById(sdcBusiQcMrlist);
                            if (b) {
                                SdcBusiQcMrlislogEntity sdcBusiQcMrlislogEntity = new SdcBusiQcMrlislogEntity();
                                sdcBusiQcMrlislogEntity.setMrlistId(sdcBusiQcMrlist.getId());
                                sdcBusiQcMrlislogEntity.setOperState("O");
                                sdcBusiQcMrlislogEntity.setOperUser("系统");
                                sdcBusiQcMrlislogEntity.setOperDate(nowDate);
                                sdcBusiQcMrlislogEntity.setOperResume("原入组条件改变");
                                boolean insert1 = sdcBusiQcMrlislogService.insert(sdcBusiQcMrlislogEntity);
                            }
                            inthe = new SdsQcentityEntity();
                        }
                    }
                } else {
                    sdcBusiQcMrlist.setOutDate(nowDate);
                    sdcBusiQcMrlist.setOutTime(nowDate);
                    sdcBusiQcMrlist.setState("O");
                    boolean b = sdcBusiQcMrlistService.updateById(sdcBusiQcMrlist);
                    if (b) {
                        SdcBusiQcMrlislogEntity sdcBusiQcMrlislogEntity = new SdcBusiQcMrlislogEntity();
                        sdcBusiQcMrlislogEntity.setMrlistId(sdcBusiQcMrlist.getId());
                        sdcBusiQcMrlislogEntity.setOperState("O");
                        sdcBusiQcMrlislogEntity.setOperUser("系统");
                        sdcBusiQcMrlislogEntity.setOperDate(nowDate);
                        sdcBusiQcMrlislogEntity.setOperResume("原入组条件改变");
                        boolean insert1 = sdcBusiQcMrlislogService.insert(sdcBusiQcMrlislogEntity);
                    }
                    inthe = new SdsQcentityEntity();
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                platformTransactionManager.rollback(transactionStatus);
            }
            platformTransactionManager.commit(transactionStatus);
        }
        return inthe;
    }

    /**
     * 针对在组患者重新执行入组筛查，看是否会出组或入组其他病种
     *
     * @param params
     * @param curMrCase
     * @return 入组病种
     * @throws Exception
     */
    private SdsQcentityEntity enrollment(Map<String, Object> params, SdcBusiQcMrlistEntity curMrCase) throws Exception {
        SdsQcentityEntity inthe = new SdsQcentityEntity();

        // 当前在组病种代码
        Long curEntityId = curMrCase.getEntityId();

        // 如果当前入组记录是医生手动确认保留在组的，则不再执行出组判定和其他病种入组判定
        if (CommonUtil.equals(curMrCase.getGroupStatus(), "ActivePart") && (CommonUtil.equals(curMrCase.getState(), "I"))) {
            inthe = QcEntityCache.me().getQcEntityById(curEntityId);
            return inthe;
        }
        // 就诊号
        Long episodeId = Long.valueOf(params.get("patientId").toString());
        //遍历已经开展的质控病种
        Long entityTypeId = sdsCommonService.getDictId("QcentityType","Up");
        Wrapper<SdsQcentityEntity> wpr = new EntityWrapper<>();
        wpr.ne("is_active", 0).eq("entity_type_id",entityTypeId).orderBy("ind_no"); // 非作废病种且按照排序码排序
        List<SdsQcentityEntity> qcentityEntities = sdsQcentityService.selectList(wpr);
        a:
        for (SdsQcentityEntity sdsQcentityEntity : qcentityEntities) {
            if (CommonUtil.isNotEmpty(inthe.getId())) {
                //已入病种，退出判断
                break a;
            }
            // 如果该病种医生手动确认过不入组，则跳过该病种,防止排除的病种再次筛查
            Wrapper<SdcBusiQcMrlistEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("episode_id", episodeId)
                    .eq("entity_id", sdsQcentityEntity.getId())
                    .eq("group_status", "ActivePart")
                    .eq("state", "O");
            List<SdcBusiQcMrlistEntity> list = sdcBusiQcMrlistService.selectList(wrapper);
            if (!list.isEmpty()) {
                continue;
            }
            Map<String, Object> map2 = new HashMap<>();
            map2.put("entityId", sdsQcentityEntity.getId());
            List<SdsQcentityRuleEntity> qcentityRuleEntities = sdsQcentityRuleService.list(map2);
            //准入规则
            List<SdsQcentityRuleEntity> admits = new ArrayList<>();
            //排除规则
            List<SdsQcentityRuleEntity> exclude = new ArrayList<>();
            for (SdsQcentityRuleEntity sdsQcentityRuleEntity : qcentityRuleEntities) {
                if (!Objects.equals(1, sdsQcentityRuleEntity.getIsActive())) {
                    continue;
                }
                if (Objects.equals("1", sdsQcentityRuleEntity.getRuleType())) {
                    admits.add(sdsQcentityRuleEntity);
                } else {
                    exclude.add(sdsQcentityRuleEntity);
                }
            }
            //有准入配置，才进行入组判断
            String ret = "";
            String ruleId = "";
            if (!admits.isEmpty()) {
                //Param2:判断且伴为同一组的准入规则，排序相同的为同一组
                //String param2 = sdsQcentityRuleEntity.getParam2();
                //按Param2进行分组
                Map<String, List<SdsQcentityRuleEntity>> collect = admits.stream().collect(Collectors.groupingBy(p -> p.getParam2() == null ? "" : p.getParam2(), Collectors.toList()));
                b:
                for (String param2 : collect.keySet()) {
                    List<SdsQcentityRuleEntity> sdsQcentityRuleEntities = collect.get(param2);
                    //每一组ruleId重置
                    ruleId = "";
                    for (SdsQcentityRuleEntity sdsQcentityRuleEntity : sdsQcentityRuleEntities) {
                        ret = "N";
                        SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
                        if (!StringUtils.isEmpty(sdsExpressEntity)) {
                            Class c = Class.forName("com.dhcc.sdc.api.function.IntheCheck");
                            IntheCheck intheCheckSrv = (IntheCheck) c.newInstance();
                            Method method = c.getMethod(sdsExpressEntity.getExpress(), Long.class, String.class);
                            ret = (String) method.invoke(intheCheckSrv, episodeId, sdsQcentityRuleEntity.getParam());
                            if (!Objects.equals("Y", ret)) {
                                continue b;
                            } else {
                                //记录ruleId
                                ruleId += sdsQcentityRuleEntity.getId() + ",";
                            }
                        }
                    }
                    if (Objects.equals("Y", ret)) {
                        //多个准入，并行满足一个跳出
                        break b;
                    }
                }
                DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
                definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                TransactionStatus transactionStatus = platformTransactionManager.getTransaction(definition);
                try {
                    if (Objects.equals("Y", ret)) {
                        inthe = sdsQcentityEntity;
                        SdcBusiQcMrlistEntity sdcBusiQcMrlist = new SdcBusiQcMrlistEntity();
                        // 如果新入组病种与当前在组病种一致，继续出组判定
                        if (CommonUtil.equals(sdsQcentityEntity.getId(), curEntityId)) {
                            sdcBusiQcMrlist = curMrCase;
                        } else {
                            /*// 如果新入组病种与当前在组病种不一致，删除当前在组记录
                            sdsQcincaseService.deleteById(curMrCase.getId());
                            sdsQcincaseOperlogService.delete(new EntityWrapper<SdsQcincaseOperlogEntity>().eq("in_case_id", curMrCase.getId()));
                            // 插入新的入组记录
                            sdsQcincaseEntity.setEpisodeId(episodeId);
                            sdsQcincaseEntity.setEntityId(sdsQcentityEntity.getId());
                            sdsQcincaseEntity.setInUserId(cdcEpisodeEntity.getAdmDoctorId());
                            sdsQcincaseEntity.setInLocId(cdcEpisodeEntity.getAdmLocId());
                            sdsQcincaseEntity.setInWardId(cdcEpisodeEntity.getAdmWardId());
                            sdsQcincaseEntity.setInDate(new Date());
                            sdsQcincaseEntity.setInTime(new Date());
                            sdsQcincaseEntity.setState("I");
                            sdsQcincaseEntity.setGroupStatus("SysRec");
                            sdsQcincaseEntity.setFillingStatus("NotFilled");
                            sdsQcincaseEntity.setReportStatus("NotUp");
                            sdsQcincaseEntity.setIntheMoment("I");
                            boolean insert = sdsQcincaseService.insert(sdsQcincaseEntity);
                            if (insert) {
                                //增加病历状态记录
                                SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity = new SdsQcincaseOperlogEntity();
                                sdsQcincaseOperlogEntity.setInCaseId(sdsQcincaseEntity.getId());
                                sdsQcincaseOperlogEntity.setOperState("I");
                                sdsQcincaseOperlogEntity.setOperUser("系统");
                                sdsQcincaseOperlogEntity.setOperDate(new Date());
                                sdsQcincaseOperlogEntity.setOperReason(ruleId);
                                boolean insert1 = sdsQcincaseOperlogService.insert(sdsQcincaseOperlogEntity);
                            }*/
                        }

                        String ruleIDStr = "";
                        if (!exclude.isEmpty()) {
                            //对于符合准入条件，且有排除配置的病例，做自动排除判断
                            for (SdsQcentityRuleEntity sdsQcentityRuleEntity : exclude) {
                                SdsExpressEntity sdsExpressEntity = sdsExpressService.selectById(sdsQcentityRuleEntity.getExpressId());
                                if (!StringUtils.isEmpty(sdsExpressEntity)) {
                                    Class<?> aClass = Class.forName("com.dhcc.sdc.api.function.IntheCheck");
                                    IntheCheck intheCheckSrv = (IntheCheck) aClass.newInstance();
                                    Method method = aClass.getMethod(sdsExpressEntity.getExpress(), Long.class, String.class);
                                    ret = (String) method.invoke(intheCheckSrv, episodeId, sdsQcentityRuleEntity.getParam());

                                    if (Objects.equals("Y", ret)) {
                                        ruleIDStr = sdsQcentityRuleEntity.getId() + "";
                                        break;
                                    }
                                }
                            }
                            if (!StringUtils.isEmpty(ruleIDStr)) {
                               /* sdsQcincaseEntity.setOutDate(new Date());
                                sdsQcincaseEntity.setOutTime(new Date());
                                sdsQcincaseEntity.setState("O");
                                boolean b = sdsQcincaseService.updateById(sdsQcincaseEntity);
                                if (b) {
                                    SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity = new SdsQcincaseOperlogEntity();
                                    sdsQcincaseOperlogEntity.setInCaseId(sdsQcincaseEntity.getId());
                                    sdsQcincaseOperlogEntity.setOperState("O");
                                    sdsQcincaseOperlogEntity.setOperUser("系统");
                                    sdsQcincaseOperlogEntity.setOperDate(new Date());
                                    sdsQcincaseOperlogEntity.setOperReason(ruleIDStr);
                                    boolean insert1 = sdsQcincaseOperlogService.insert(sdsQcincaseOperlogEntity);
                                }*/
                                inthe = new SdsQcentityEntity();
                            }
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    platformTransactionManager.rollback(transactionStatus);
                }
                platformTransactionManager.commit(transactionStatus);
            }
        }
        return inthe;
    }

    /**
     * 获取患者在组病种相关禁忌症
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> getCIs(Map<String, Object> params) {
        List<Map<String, Object>> CIList = new ArrayList<>();
        String[] CIArr = params.get("itemStr").toString().split(",");


        Long episodeId = Long.valueOf(params.get("episodeId").toString()); // 就诊号

        for (String ciid : CIArr) {
            Map map = new HashMap();
            // 查询禁忌症信息
            ContraindicationEntity CIEntity = contraindicationService.selectById(ciid);
            // 获取禁忌症条目信息
            List<ContraindicationItemEntity> ciItems = contraindicationItemService.selectList(new EntityWrapper<ContraindicationItemEntity>()
                    .eq("contraindication_id", ciid).eq("active", 1));
            // 获取禁忌症选中信息
            String cIds = "#";
            JSONObject itemObj = new JSONObject();
            Wrapper<SdcBusiContraindicationDtlEntity> bw = new EntityWrapper<SdcBusiContraindicationDtlEntity>();
            bw.eq("episode_id", episodeId).eq("contraindication_id", ciid).eq("status", 1).orderBy("item_id", true);
            List<SdcBusiContraindicationDtlEntity> cidList = sdcBusiContraindicationDtlMapper.selectList(bw);
            for (SdcBusiContraindicationDtlEntity dtl : cidList) {
                Long id = dtl.getItemId();
                cIds += id + "#";
                if (dtl.getMannul() == 1){
                    //手动
                    String time = DateUtil.getTime(dtl.getTriggerDate());
                    itemObj.put(id + "", dtl.getMannul() + "^" + dtl.getKeyWords() + ":" + dtl.getKeyWordsfrom() + " " + time);
                }else {
                    //系统
                    itemObj.put(id + "", dtl.getMannul() + "^" + dtl.getKeyWords() + ":" + dtl.getKeyWordsfrom() );
                }
            }
            // 患者数据自动匹配禁忌条目规则
            for (ContraindicationItemEntity ciItem : ciItems) {
                // 若临床医生审核过该禁忌条目则以医生为主
                Map<String, Object> inMap = new HashMap<>();
                inMap.put("episode_id", episodeId);
                inMap.put("item_id", ciItem.getId());
                List<SdcBusiContraindicationDtlEntity> dtl = sdcBusiContraindicationDtlMapper.selectByMap(inMap);
                if (dtl.size() > 0) {
                    continue;
                }
                String expression = ciItem.getExpression();
                if (CommonUtil.isNotEmpty(expression)) {
                    Map<String,Object> res = (Map)isdsStandRuleCalService.handleRuleExpressions(expression, episodeId, null);
                    boolean bool = (boolean)res.get("bool");
                    if (bool) {
                        cIds += ciItem.getId() + "#";
                        itemObj.put(ciItem.getId() + "", 0 + "^系统自动匹配");
                    }
                }
            }

            map.put("CIInfo", CIEntity);
            map.put("CIItems", ciItems);
            map.put("CIDtls", cIds);
            map.put("ItemObjs", itemObj);

            CIList.add(map);
        }
        return CIList;
    }

    /**
     * 获取禁忌症信息包括结果值
     *
     * @param itemId
     * @param inCaseId
     * @return
     */
    private Map<String, Object> getCIItemInfo(long itemId, long inCaseId) {
        Map<String, Object> map = new HashMap<>();
        // 查询项目信息及结果
        Map<String, Object> itemInfo = sdsToolSdkMapper.getItemInfo(itemId, inCaseId);
        String inpItemType = CommonUtil.isEmpty(itemInfo.get("itemType")) ? "" : itemInfo.get("itemType").toString();
        String inpItemResult = CommonUtil.isEmpty(itemInfo.get("itemResult")) ? "" : itemInfo.get("itemResult").toString();
        Wrapper<SdsQcfitemDicEntity> inpDicWpr = new EntityWrapper<>();
        inpDicWpr.eq("form_item_id", itemId).eq("is_active", 1).ne("code", "def");
        List<SdsQcfitemDicEntity> inpItemDics = sdsQcfitemDicMapper.selectList(inpDicWpr);
        map.put("itemId", itemId);
        map.put("itemType", inpItemType);
        map.put("itemResult", inpItemResult);
        map.put("ciItems", inpItemDics);
        return map;
    }

    /**
     * 保存相关禁忌确认结果
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCiInfo(Map<String, Object> params) {
        Long episodeId = Long.valueOf(params.get("episodeId").toString());
        String modifyUser = params.get("modifyUserName").toString();
        JSONObject ciSelectObj = JSONObject.parseObject(params.get("ciSelectObj").toString());
        JSONObject ciModifyObj = JSONObject.parseObject(params.get("ciModifyObj").toString());
        Date now = new Date();
        String nowStr = DateUtil.getTime();
        for (String cid : ciModifyObj.keySet()) {
            JSONArray modidfyArr = ciModifyObj.getJSONArray(cid);
            for (int i = 0; i < modidfyArr.size(); i++) {
                JSONObject modifyObj = modidfyArr.getJSONObject(i);
                Long itemId = modifyObj.getLong("itemId");
                int operation = modifyObj.getInteger("operation");
                if (operation == 0) {// 逻辑删除
                    HashMap<String, Object> queryMap = new HashMap<>();
                    queryMap.put("episode_id", episodeId);
                    queryMap.put("contraindication_id", cid);
                    queryMap.put("item_id", itemId);
                    List<SdcBusiContraindicationDtlEntity> sdcBusiContraindicationDtlEntities = sdcBusiContraindicationDtlMapper.selectByMap(queryMap);
                    if (sdcBusiContraindicationDtlEntities.size() == 0) {
                        SdcBusiContraindicationDtlEntity dtlEntity = new SdcBusiContraindicationDtlEntity();
                        dtlEntity.setEpisodeId(episodeId);
                        dtlEntity.setContraindicationId(Long.valueOf(cid));
                        dtlEntity.setItemId(itemId);
                        dtlEntity.setTriggerDate(now);
                        dtlEntity.setKeyWords("临床确认");
                        dtlEntity.setMannul(1);
                        dtlEntity.setStatus(0);
                        dtlEntity.setKeyWordsfrom(modifyUser);
                        sdcBusiContraindicationDtlMapper.insert(dtlEntity);
                    } else {
                        sdcBusiContraindicationDtlMapper.updateForSet("mannul=1,status=0,update_date='" + nowStr + "'",
                                new EntityWrapper<SdcBusiContraindicationDtlEntity>().eq("episode_id", episodeId).
                                        eq("contraindication_id", cid).eq("item_id", itemId));
                    }
//                    sdcBusiContraindicationDtlMapper.logicDelete(modifyObj);
                } else {
                    SdcBusiContraindicationDtlEntity dtlEntity = new SdcBusiContraindicationDtlEntity();
                    dtlEntity.setEpisodeId(episodeId);
                    dtlEntity.setContraindicationId(Long.valueOf(cid));
                    dtlEntity.setItemId(itemId);
                    dtlEntity.setTriggerDate(now);
                    dtlEntity.setKeyWords("临床确认");
                    dtlEntity.setMannul(1);
                    dtlEntity.setStatus(1);
                    dtlEntity.setKeyWordsfrom(modifyUser);
                    sdcBusiContraindicationDtlMapper.insert(dtlEntity);
//                    sdcBusiContraindicationDtlMapper.insertItemModify(modifyObj);
                }
            }
        }


        for (String cid : ciSelectObj.keySet()) {
            String selectIds = ciSelectObj.getString(cid);
            int result = 0;
            if (CommonUtil.isNotEmpty(selectIds) && selectIds.split("#").length > 0) {
                result = 1;
            }

            SdcBusiContraindicationHisEntity ciHis = new SdcBusiContraindicationHisEntity();
            // 更新his表
            ciHis.setEpisodeId(episodeId);
            ciHis.setContraindicationId(Long.valueOf(cid));
            ciHis.setItemIds(selectIds);
            ciHis.setResult(result);
            ciHis.setEvalDate(now);
            ciHis.setEvalDocName(modifyUser);
            sdcBusiContraindicationHisMapper.insert(ciHis);

            // 更新结果表
            SdcBusiContraindicationEntity re = new SdcBusiContraindicationEntity();
            Wrapper<SdcBusiContraindicationEntity> warpper = new EntityWrapper<>();
            warpper.eq("episode_id", episodeId).eq("contraindication_id", cid);
            int count1 = sdcBusiContraindicationMapper.selectCount(warpper);

            if (count1 > 0) {
                sdcBusiContraindicationMapper.updateForSet("result=" + result + ",update_date='" + nowStr + "'", warpper);
            } else {
                re.setEpisodeId(episodeId);
                re.setContraindicationId(Long.valueOf(cid));
                re.setResult(result);
                re.setEvalDate(now);
                re.setUpdateDate(now);
                sdcBusiContraindicationMapper.insert(re);
            }
        }
    }

    /**
     * 获取患者在组病种相关评估量表
     *
     * @param entityId, episodeId
     * @return
     */
    public JSONObject getAsmtInfo(Long entityId, Long episodeId) {
        JSONObject dicObj = new JSONObject();
        JSONArray hasDoItems = new JSONArray();
        JSONArray planDoItems = new JSONArray();
        JSONObject item = new JSONObject();
        // 病种关联的各评估表
        List<Map<String, Object>> asmtList = sdsToolSdkMapper.getASMTList(entityId, episodeId);
        for (Map<String, Object> map : asmtList) {
            item = new JSONObject();
            item.put("id", map.get("asmtId")); // 评标表id
            item.put("text", map.get("asmtName")); // 评估表名称
            item.put("code", map.get("asmtCode")); // 评估表代码
            item.put("eventId", map.get("eventId")); // 事件id
            item.put("result", map.get("asmtResult")); // 评估结果
            item.put("score", map.get("asmtScore")); // 评估分数
            item.put("evalId", map.get("evalId")); // 评估分数
            if (CommonUtil.isEmpty(map.get("evalId"))) {
                planDoItems.add(item);
            } else {
                hasDoItems.add(item);
            }
        }
        if (planDoItems.size() != 0 || hasDoItems.size() != 0) {
            dicObj.put("type", type_qc);
            dicObj.put("plan", planDoItems);
            dicObj.put("has", hasDoItems);
        }

        return dicObj;
    }

    /**
     * 获取评估历史
     *
     * @param params
     * @return
     */
    @Override
    public Object getAsmtNodes(Map<String, Object> params) {
        List<Map<String, Object>> asmtNodes = sdsToolSdkMapper.getASMTNodes(params);
        return asmtNodes;
    }

    /**
     * 获取评估量表信息
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> getAsmtInfo(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<String, Object>();
        Long patientId = Long.valueOf(params.get("patientId").toString());
        Long entityId = Long.valueOf(params.get("entityId").toString());
        Long asmtId = Long.valueOf(params.get("asmtId").toString());

        // 获取量表条目和触发结果
        List<Map<String, Object>> asmtItems = sdsToolSdkMapper.getASMTItems(asmtId);
        for (int i = 0; i < asmtItems.size(); i++) {
            Map item = asmtItems.get(i);
            // 获取条目具体选择项
            Long itemId = Long.valueOf(item.get("itemId").toString());
            List<Map<String, Object>> asmtItemDics = sdsToolSdkMapper.getASMTItemDics(itemId);
            asmtItems.get(i).put("itemDics", asmtItemDics);
        }
        // 获取量表分值区间
        List<Map<String, Object>> asmtJudgeRange = sdsToolSdkMapper.getASMTJudgeRange(asmtId);
        // 获取量表配置节点
        List<Map<String, Object>> asmtNodeTypes = sdsToolSdkMapper.getAsmtNodeTypes(asmtId);

        result.put("asmtItems", asmtItems);
        result.put("levelRange", asmtJudgeRange);
        result.put("asmtNodeMap", asmtNodeTypes);
        return result;
    }

    @Override
    public Object getAsmtNode(Map<String, Object> params) {
        List<Map<String, Object>> asmtNode = sdsToolSdkMapper.getASMTNode(params);
        return asmtNode;
    }

    /**
     * 保存自动评估信息
     *
     * @param params
     */
    @Override
    public void saveAiNodeInfo(Map<String, Object> params) {
        Long patientId = Long.valueOf(params.get("patientId").toString());
        Long entityId = Long.valueOf(params.get("entityId").toString());
        Long asmtId = Long.valueOf(params.get("asmtId").toString());
        List<Map<String, Object>> asmtItems = sdsToolSdkMapper.getASMTItems(asmtId);
        for (int i = 0; i < asmtItems.size(); i++) {
            Map item = asmtItems.get(i);
            // 获取条目具体选择项
            Long itemId = Long.valueOf(item.get("itemId").toString());
            List<Map<String, Object>> asmtItemDics = sdsToolSdkMapper.getASMTItemDics(itemId);
            for (Map<String, Object> asmtItemDic : asmtItemDics) {
                //获取计算公式formula 判断规则
                if (asmtItemDic.containsKey("formula")) {
                    Object formula = asmtItemDic.get("formula");
                    if (!StringUtils.isEmpty(formula) && formula != null) {
                        String formulaStr = formula.toString();
                        //handleRuleExpressions()返回值修改map:ruleCodeList+bool
//                        boolean bool = isdsStandRuleCalService.handleRuleExpressions(formulaStr, patientId);
                        Map<String,Object> res = (Map)isdsStandRuleCalService.handleRuleExpressions(formulaStr, patientId,null);
                        Long dicId = (Long) asmtItemDic.get("dicId");
                        SdcBusiEvaluationHisEntity sdcBusiEvaluationHisEntity = new SdcBusiEvaluationHisEntity();
                        sdcBusiEvaluationHisEntity.setEpisodeId(patientId);
                        sdcBusiEvaluationHisEntity.setAssessmentEntryId(dicId);
                        sdcBusiEvaluationHisEntity.setAssessmentId(asmtId);
                        int auto = 1;
                        sdcBusiEvaluationHisEntity.setAuto(auto);
                        String modifyUserName = "系统";
                        //临床端自动评估 comeFrom = 0
                        int comeFrom = 0;
                        sdcBusiEvaluationHisEntity.setComeFrom(comeFrom);
                        sdcBusiEvaluationHisEntity.setEvalDocName(modifyUserName);
                        SdcBusiEvaluationHisEntity sdcBusiEvaluationHisEntity1 = sdcBusiEvaluationHisMapper.selectOne(sdcBusiEvaluationHisEntity);
                        boolean bool = (boolean)res.get("bool");
                        if (bool) {
                            //匹配评估规则  如果没有历史保存过则保存/如果历史保存过则删除历史、保存本次
                            sdcBusiEvaluationHisEntity.setResult("");
                            sdcBusiEvaluationHisEntity.setEvalDate(new Date());
                            String keyWordsfrom = "";
                            String keyWordsfroms = "";
                            //拼接规则如   基本信息：年龄≥65岁
                            List<String> ruleCodeList = (List<String>) res.get("ruleCodeList");
                            if(!CollectionUtils.isEmpty(ruleCodeList)){
                                for (int i1 = 0; i1 < ruleCodeList.size(); i1++) {
                                    Wrapper<SdsStandRuleBaseEntity> wrapper = new EntityWrapper<>();
                                    wrapper.eq("rule_code", ruleCodeList.get(i1));
                                    SdsStandRuleBaseEntity sdsStandRuleBaseEntity = iSdsStandRuleBaseService.selectOne(wrapper);
                                    String ruleType = sdsStandRuleBaseEntity.getRuleType();
                                    String ruleDesc = sdsStandRuleBaseEntity.getRuleDesc();
                                    if (!StringUtils.isEmpty(ruleType) && !StringUtils.isEmpty(ruleDesc)) {
                                        keyWordsfrom = ruleType + ":" + ruleDesc;
                                        if(ruleCodeList.size()>1&&i1<ruleCodeList.size()-1){
                                            keyWordsfroms+=keyWordsfrom+"且";
                                        }
                                        if(i1==ruleCodeList.size()-1){
                                            keyWordsfroms+=keyWordsfrom;
                                        }
                                    }
                                }
                            }
                            sdcBusiEvaluationHisEntity.setKeyWordsfrom(keyWordsfroms);
//                            evalItemId表示t_sdc_busi_evaluation_item的id  自动评估无法取值
//                            sdcBusiEvaluationHisEntity.setEvalItemId(evalItemId);
                            SdcBaseAssessmenentryEntity sdcBaseAssessmenentryEntity = sdcBaseAssessmenentryMapper.selectById(dicId);
                            String score1 = sdcBaseAssessmenentryEntity.getScore();
                            Float score;
                            if(score1.contains("分")){
                                score=Float.parseFloat(score1.replace("分",""));
                            }else {
                                score= Float.parseFloat(score1);
                            }
                            sdcBusiEvaluationHisEntity.setScore(score);

                            if (sdcBusiEvaluationHisEntity1 != null) {
                                sdcBusiEvaluationHisEntity1.deleteById();
                                sdcBusiEvaluationHisEntity.insert();
                            }else {
                                sdcBusiEvaluationHisEntity.insert();
                            }
                        } else {
                            //不匹配规则，可能是信息变动，需要查该评估项是否已经存表、有则删除
                            if (sdcBusiEvaluationHisEntity1 != null) {
                                sdcBusiEvaluationHisEntity1.deleteById();
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
        }
    }

    @Override
    public Object getNodeInfo(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<String, Object>();
        Wrapper<SdcBusiEvaluationItemEntity> wpr = new EntityWrapper<>();
        wpr.eq("evaluation_id", params.get("evalId"));
        return sdcBusiEvaluationItemMapper.selectList(wpr);
    }


    /**
     * 保存相关评估量表
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAsmtInfo(Map<String, Object> params) {
        Long patientId = Long.valueOf(params.get("patientId").toString());
        Long asmtId = Long.valueOf(params.get("asmtId").toString());
        String nodeId = params.get("nodeId").toString().replace("$", "|");
        Long evalId = Long.valueOf(params.get("evalId").toString());
        Float score = Float.valueOf(params.get("score").toString());
        String level = params.get("level").toString();
        String modifyUserName = "";
        if (!StringUtils.isEmpty(params.get("modifyUserName"))){
             modifyUserName = params.get("modifyUserName").toString();
        }
        Long nodeType = null;
        if (CommonUtil.isNotEmpty(params.get("nodeType"))) {
            nodeType = Long.valueOf(params.get("nodeType").toString());
        }
        JSONArray asmtArr = JSONArray.parseArray(params.get("sdsAsmtData").toString());
        JSONArray asmtAutoArr = JSONArray.parseArray(params.get("sdsAsmtAutoData").toString());

        Date now = new Date();
        // 更新保存评估结果
        SdcBusiEvaluationEntity evaluation = new SdcBusiEvaluationEntity();
        evaluation.setAssessmentId(asmtId);
        evaluation.setEpisodeId(patientId);
        evaluation.setScore(score);
        evaluation.setLevel(level);
        evaluation.setUpdateDate(now);
        evaluation.setUpdateName(modifyUserName);
        if (CommonUtil.equals(evalId, 0L)) {
            // 新增
            evaluation.setCreateDate(now);
            evaluation.setNodeId(nodeType);
            evaluation.insert();
            evalId = evaluation.getId();
        } else {
            // 更新
            evaluation.setId(evalId);
            evaluation.updateById();
        }
        // 更新保存明细
        SdcBusiEvaluationItemEntity evaluationItem = new SdcBusiEvaluationItemEntity();
        evaluationItem.setEvaluationId(evalId);
        // 先全部删除再重新插入
        Wrapper<SdcBusiEvaluationItemEntity> eiWpr = new EntityWrapper<>();
        eiWpr.eq("evaluation_id", evalId);
        sdcBusiEvaluationItemMapper.delete(eiWpr);
        a:for (Object asmtItemId : asmtArr) {
            boolean falg = false;
            b:for (Object asmtAutoItemId : asmtAutoArr){
                if ((asmtItemId.toString()).equals(asmtAutoItemId.toString())){
                    falg = true;
                    break b;
                }
            }
            evaluationItem = new SdcBusiEvaluationItemEntity();
            evaluationItem.setEvaluationId(evalId);
            evaluationItem.setAssessmentEntryId(Long.valueOf(asmtItemId.toString()));
            evaluationItem.setUptateTime(now);
            if (falg){
                //自动
                evaluationItem.setManual(0);
            }else {
                //手动
                evaluationItem.setManual(1);
            }
            evaluationItem.insert();
            updateBusiEvaluationHis(Long.valueOf(asmtItemId.toString()), patientId, falg, evaluationItem.getId(), modifyUserName, asmtId);
        }
    }

    @Override
    public Object confirmInDis(Map<String, Object> params) {
        Long newDisId = null;
        if (CommonUtil.isNotEmpty(params.get("newDisId"))) {
            newDisId = Long.valueOf(params.get("newDisId").toString());
        }
        Long episodeId = Long.valueOf(params.get("episodeId").toString());
        String modifyUserId = "", modifyUserName = "";
        if (CommonUtil.isNotEmpty(params.get("modifyUserId"))) {
            modifyUserId = params.get("modifyUserId").toString();
        }
        if (CommonUtil.isNotEmpty(params.get("modifyUserName"))) {
            modifyUserName = params.get("modifyUserName").toString();
        }
        // 查询数据中心的对应的就诊id
        Map map = new HashMap();
        map.put("xcode", episodeId);
        List<CdcEpisodeEntity> cdcEpisods = cdcEpisodeService.list(map);
        if (cdcEpisods.size() == 0) {
            return -1;
        }
        CdcEpisodeEntity episodeEntity = cdcEpisods.get(0);
        episodeId = episodeEntity.getId();
        //新增入组记录
        Date nowDate = new Date();
        SdcBusiQcMrlistEntity sdcBusiQcMrlistEntity = new SdcBusiQcMrlistEntity();
        sdcBusiQcMrlistEntity.setEpisodeId(episodeId);
        sdcBusiQcMrlistEntity.setEntityId(newDisId);
        sdcBusiQcMrlistEntity.setInUserId(String.valueOf(episodeEntity.getAdmDoctorId()));
        sdcBusiQcMrlistEntity.setInLocId(String.valueOf(episodeEntity.getAdmLocId()));
        sdcBusiQcMrlistEntity.setInWardId(String.valueOf(episodeEntity.getAdmWardId()));
        sdcBusiQcMrlistEntity.setInDate(nowDate);
        sdcBusiQcMrlistEntity.setInTime(nowDate);
        sdcBusiQcMrlistEntity.setState("I");
        sdcBusiQcMrlistEntity.setGroupStatus("SysRec");
        boolean insert = sdcBusiQcMrlistService.insert(sdcBusiQcMrlistEntity);
        if (insert) {
            //增加病历状态记录
            SdcBusiQcMrlislogEntity sdcBusiQcMrlislogEntity = new SdcBusiQcMrlislogEntity();
            sdcBusiQcMrlislogEntity.setMrlistId(sdcBusiQcMrlistEntity.getId());
            sdcBusiQcMrlislogEntity.setOperState("I");
            sdcBusiQcMrlislogEntity.setOperUser(modifyUserName);
            sdcBusiQcMrlislogEntity.setOperDate(nowDate);
            sdcBusiQcMrlislogEntity.setOperResume("在院过程质控入组");
            boolean insert1 = sdcBusiQcMrlislogService.insert(sdcBusiQcMrlislogEntity);
        }
        // 获取病种信息
        SdsQcentityEntity entity = QcEntityCache.me().getQcEntityById(newDisId);
        Map hisMap = new HashMap();
        hisMap.put("episodeId", params.get("episodeId"));
        hisMap.put("diseaseType", entity.getBtDesc());
        hisMap.put("modifyUser", modifyUserId);
        hisMap.put("isActive", "1");
        // 向his推送患者入组数据
        this.pushIntheInfo2His(hisMap);

        return 1;
    }

    @Override
    public Object confirmOutDis(Map<String, Object> params) {
        Long curMrListId = null;
        if (CommonUtil.isNotEmpty(params.get("curMrListId"))) {
            curMrListId = Long.valueOf(params.get("curMrListId").toString());
        }
        Long newDisId = null;
        if (CommonUtil.isNotEmpty(params.get("newDisId"))) {
            newDisId = Long.valueOf(params.get("newDisId").toString());
        }
        Long episodeId = Long.valueOf(params.get("episodeId").toString());
        String modifyUserId = "", modifyUserName = "";
        if (CommonUtil.isNotEmpty(params.get("modifyUserId"))) {
            modifyUserId = params.get("modifyUserId").toString();
        }
        if (CommonUtil.isNotEmpty(params.get("modifyUserName"))) {
            modifyUserName = params.get("modifyUserName").toString();
        }
        // 查询数据中心的对应的就诊id
        Map map = new HashMap();
        map.put("xcode", episodeId);
        List<CdcEpisodeEntity> cdcEpisods = cdcEpisodeService.list(map);
        if (cdcEpisods.size() == 0) {
            return -1;
        }
        CdcEpisodeEntity episodeEntity = cdcEpisods.get(0);
        episodeId = episodeEntity.getId();

        Map hisMap = new HashMap();

        // 修改入组记录
        Date nowDate = new Date();
        SdcBusiQcMrlistEntity mrList = sdcBusiQcMrlistService.selectById(curMrListId);
        if (mrList != null) {
            mrList.setOutDate(nowDate);
            mrList.setOutTime(nowDate);
            mrList.setState("O");
            boolean b = sdcBusiQcMrlistService.updateById(mrList);
            //出组时删除过程质控触发项
            Wrapper<SdcBusiQcTriggeredEntity> triWrapper = new EntityWrapper<SdcBusiQcTriggeredEntity>() ;
            triWrapper.eq("episode_id",mrList.getEpisodeId());
            sdcBusiQcTriggeredMapper.delete(triWrapper);
            if (b) {
                //增加病历状态记录
                SdcBusiQcMrlislogEntity sdcBusiQcMrlislogEntity = new SdcBusiQcMrlislogEntity();
                sdcBusiQcMrlislogEntity.setMrlistId(mrList.getId());
                sdcBusiQcMrlislogEntity.setOperState("O");
                sdcBusiQcMrlislogEntity.setOperUser(modifyUserName);
                sdcBusiQcMrlislogEntity.setOperDate(nowDate);
                sdcBusiQcMrlislogEntity.setOperResume("在院过程质控出组");
                boolean insert1 = sdcBusiQcMrlislogService.insert(sdcBusiQcMrlislogEntity);
            }

            // 获取病种信息
            SdsQcentityEntity entity = QcEntityCache.me().getQcEntityById(mrList.getEntityId());
            hisMap.put("diseaseType", entity.getBtDesc());
            hisMap.put("isActive", "0");
        }
        // 新病种入组
        if (CommonUtil.isNotEmpty(newDisId)) {
            SdcBusiQcMrlistEntity sdcBusiQcMrlistEntity = new SdcBusiQcMrlistEntity();
            sdcBusiQcMrlistEntity.setEpisodeId(episodeId);
            sdcBusiQcMrlistEntity.setEntityId(newDisId);
            sdcBusiQcMrlistEntity.setInUserId(String.valueOf(episodeEntity.getAdmDoctorId()));
            sdcBusiQcMrlistEntity.setInLocId(String.valueOf(episodeEntity.getAdmLocId()));
            sdcBusiQcMrlistEntity.setInWardId(String.valueOf(episodeEntity.getAdmWardId()));
            sdcBusiQcMrlistEntity.setInDate(nowDate);
            sdcBusiQcMrlistEntity.setInTime(nowDate);
            sdcBusiQcMrlistEntity.setState("I");
            sdcBusiQcMrlistEntity.setGroupStatus("SysRec");
            boolean insert = sdcBusiQcMrlistService.insert(sdcBusiQcMrlistEntity);
            if (insert) {
                //增加病历状态记录
                SdcBusiQcMrlislogEntity sdcBusiQcMrlislogEntity = new SdcBusiQcMrlislogEntity();
                sdcBusiQcMrlislogEntity.setMrlistId(sdcBusiQcMrlistEntity.getId());
                sdcBusiQcMrlislogEntity.setOperState("I");
                sdcBusiQcMrlislogEntity.setOperUser(modifyUserName);
                sdcBusiQcMrlislogEntity.setOperDate(nowDate);
                sdcBusiQcMrlislogEntity.setOperResume("在院过程质控入组");
                boolean insert1 = sdcBusiQcMrlislogService.insert(sdcBusiQcMrlislogEntity);
            }

            // 获取病种信息
            SdsQcentityEntity entity = QcEntityCache.me().getQcEntityById(newDisId);
            hisMap.put("diseaseType", entity.getBtDesc());
            hisMap.put("isActive", "1");
        }

        hisMap.put("episodeId", params.get("episodeId"));
        hisMap.put("modifyUser", modifyUserId);
        // 向his推送患者入组数据
        this.pushIntheInfo2His(hisMap);

        return 1;
    }

    @Override
    public JSONArray getOrderInfo(Map<String, Object> params) {
        JSONArray jsonArray = new JSONArray();


        String planType = params.get("planType").toString();
        String entityId = params.get("entityId").toString();

        if (params.get("itemId") != null) {
            String itemStr = params.get("itemId").toString();
            String[] itemArr = itemStr.split(",");
            for (String item : itemArr) {
                if (CommonUtil.isEmpty(item)) continue;
                jsonArray.addAll(getOrderMasterByItemId(entityId, item, planType));
            }
        }

        return jsonArray;
    }

    /**
     * 获取item关联的医嘱项信息
     *
     * @param entityId
     * @param itemId
     * @param planType
     * @return
     */
    private JSONArray getOrderMasterByItemId(String entityId, String itemId, String planType) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONArray itemArray = new JSONArray();
        Map params = new HashMap();
        params.put("itemId", itemId);
        params.put("entityId", entityId);
        // 获取关联对照医嘱项
        //获取item信息
        Wrapper<SdcCdssItemEntity> treatWpr = new EntityWrapper<>();
        treatWpr.eq("item_id", itemId).eq("qcentity_id", entityId);
        List<SdcCdssItemEntity> SdcCdssTreatList = sdcCdssItemMapper.selectList(treatWpr);
        String itemName = SdcCdssTreatList.get(0).getItemName();

        List<SdcCdssItemMatchEntity> orderList = sdcCdssItemMatchMapper.list(params);
        // 查询医嘱
        for (SdcCdssItemMatchEntity orderMatch : orderList) {
            // 查询医嘱信息
            CdcOrdmastEntity ordMast = cdcOrdmastMapper.selectById(orderMatch.getMatchId());
            if (CommonUtil.isEmpty(ordMast)) {
                CdcOrdgroupEntity ordgroup = cdcOrdgroupMapper.selectById(orderMatch.getMatchId());
                if (CommonUtil.isEmpty(ordgroup)){
                    continue;
                }
                ordgroup.setIsActive(orderMatch.getIsDefault());
                itemArray.add(ordgroup);
                continue;
            }
            if(ordMast.getIsActive() == 0 || ordMast.getDelFlag()){
                continue;
            }
            ordMast.setIsActive(orderMatch.getIsDefault());
            itemArray.add(ordMast);
        }
        jsonObject.put("itemName", itemName);
        jsonObject.put("itemList", itemArray);
        jsonArray.add(jsonObject);

        return jsonArray;
    }

    /**
     * @param params = 11||1#12||2#13||1  多个医嘱项id以#分割
     *               Input:       EpisodeID:就诊ID,必填项;LocDr:使用科室ID(CT_Loc),非必填，指定使用科室时传入;UserDr:使用用户ID(SS_User),非必填，指定使用用户时传入;
     *               CopyItemList:以$c(1)分割的医嘱信息串，例：OneItemStr_$C(1)_OneItemStr_$C(1)_OneItemStr
     *               OneItemStr说明:以^分割的数据串,*为必填标识
     *               序号^*医嘱项ID^单次剂量^单次剂量单位ID^频次ID^用法ID^
     *               ^疗程ID^整包装数量^整包装数量单位ID^医嘱优先级ID^医嘱套ID
     *               ^医嘱备注^*是否加急(N|Y)^医嘱套项目ID^检验标本代码^接受科室ID(未实现)
     *               ^费别
     *               序号:非关联医嘱为自增,关联医嘱的子医嘱为[主医嘱序号.子医嘱序号]。例如序号1有两条子医嘱，第一条子医嘱为1.1，第二条子医嘱为1.2；第二组医嘱的序号分别为2，2.1，2.2
     *               Return:      0：成功 其他：失败
     *               Others:      w ##class(DHCDoc.Interface.Inside.Service).InsertCopyItem(62,"","","1^311||1"_$C(1)_"2^312||1")
     * @Description：医嘱项插入东华HIS中
     * @Title: addOrderToHis
     */
    @Override
    public String addOrderToHis(Map<String, Object> params) {
        String orderIds = params.get("orderIds").toString();
        String episodeId = params.get("episodeId").toString();

        String orderList = "";
        String backInfo = "";
        String[] tempString = orderIds.split("#");
        List<String> temps = Arrays.asList(tempString);
        List<String> orders = new ArrayList<>();
        for (String s : temps){
           CdcOrdgroupEntity temp = new CdcOrdgroupEntity();
           temp.setXcode(s);
           CdcOrdgroupEntity cdcOrdgroup = cdcOrdgroupMapper.selectOne(temp);
           if (CommonUtil.isEmpty(cdcOrdgroup)){
               orders.add(s);
               continue;
           }
           Wrapper<CdcOrdgroupEntryEntity> wrapper = new EntityWrapper<>();
           wrapper.eq("order_group_id",cdcOrdgroup.getId());
           List<CdcOrdgroupEntryEntity> ordList = cdcOrdgroupEntryMapper.selectList(wrapper);
           for (CdcOrdgroupEntryEntity ord : ordList){
               CdcOrdmastEntity ordmast = cdcOrdmastMapper.selectById(ord.getOrderMastId());
               if (CommonUtil.isNotEmpty(ordmast)){
                   orders.add(ordmast.getXcode());
               }
           }
        }
        String[] orderIdArr = orders.toArray(new String[orders.size()]);
        for (int i = 0; i < orderIdArr.length; i++) {
            //134||1^S 134||1^NORM，S和NORM为优先级 S长期 NORM临时
            orderList += (i + 1) + "^" + orderIdArr[i] + "^^^^^^^^" + "NORM" + "^^^N^^^^" + "#";
        }
        logger.info("插入HIS中的医嘱串：" + orderList);

        if (CommonUtil.isNotEmpty(orderList)) {
            if (dhcHisInterfaceHead) {//有Head验证
                AddVteOrderWebServiceLocator locator = new AddVteOrderWebServiceLocator();
                try {
                    AddVteOrderWebServiceSoap soap = locator.getAddVteOrderWebServiceSoap(dhcHisCacheIp, dhcHisCachePath);
                    backInfo = soap.addVteOrder(episodeId, null, null, orderList);
                } catch (ServiceException e) {
                    e.printStackTrace();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else {
                Map<String, Object> data = new LinkedHashMap<>();
                data.put("EpisodeID", episodeId);
                data.put("LocDr", null);
                data.put("UserDr", null);
                data.put("OrderList", orderList);
                try {
                    backInfo = HttpClientServiceFactory.getImporter(ServiceType.SOAP)
                            .importService("http://" + dhcHisCacheIp + ":57772/" + dhcHisCachePath + "/DHCMA.VTE.AddVteOrderWebService.CLS?WSDL=1").getEndpoint("AddVteOrder")
                            .buildInvocation(data).invoke().response().toString();
                } catch (ServiceImportException e) {
                    e.printStackTrace();
                }
            }
        }
        return backInfo;
    }

    /**
     * @throws
     * @Description:向his推送SDS数据
     * @Title: pushHisIntheInfo
     * @return: void
     * @author: sunyingjie
     * @date:2023年3月15日 下午1:21:26
     */
    @Override
    @Async
    public void pushIntheInfo2His(Map<String, Object> params) {

        String episodeId = (String) params.get("episodeId");
        String diseaseType = (String) params.get("diseaseType");
        String modifyUser = (String) params.get("modifyUser");
        String isActive = (String) params.get("isActive");

        //拼接字符串<拼接成his系统能识别的字符串>
        String intheDataStr = episodeId + "^" + diseaseType + "^" + DateUtil.getTime() + "^" + modifyUser + "^" + isActive;
        logger.info("推送的字符串：" + intheDataStr);
        String backInfo = "";
        if (dhcHisInterfaceHead) {
            //在一个方法中连续调用多次WebService接口,每次调用前需要重置上下文
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            //调用护士床位图HIS存储接口WebService
            SdsIntheCaseServiceLocator dhcLocator = new SdsIntheCaseServiceLocator();
            try {
                SdsIntheCaseServiceSoap soap = dhcLocator.getSdsIntheCaseServiceSoap(dhcHisCacheIp, dhcHisCachePath);
                backInfo = soap.storeIntheCase(intheDataStr);
                Thread.currentThread().setContextClassLoader(cl);
            } catch (ServiceException e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        } else {
            //调用接口的API方法
            //在一个方法中连续调用多次WebService接口,每次调用前需要重置上下文
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();

            Client client = dcf.createClient(dhcHisCacheIp + dhcHisCachePath + "/DHCMA.SDS.SdsIntheCaseService.CLS?WSDL=1");

            Object[] objects = new Object[11];
            try {
                objects = client.invoke("StoreIntheCase", intheDataStr);
                Thread.currentThread().setContextClassLoader(cl);
                backInfo = objects[0].toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        logger.info("单病种过程质控入组情况推送给HIS返回结果：" + backInfo);

    }

    @Override
    public Map<String, Object> getPrintInfo(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<String, Object>();
        Long entityId = Long.valueOf(params.get("entityId").toString());
        Long asmtId = Long.valueOf(params.get("asmtId").toString());
        Long patientId = Long.valueOf(params.get("patientId").toString());
        Long evalId = Long.valueOf(params.get("evalId").toString());

        SdsQcentityEntity sdsQcentityEntity = sdsQcentityService.selectById(entityId);
        SdcBaseAssessmentEntity sdcBaseAssessmentEntity = sdcBaseAssessmentMapper.selectById(asmtId);
        CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeService.selectById(patientId);
        List<Map<String, Object>> asmtItems = sdsToolSdkMapper.getASMTItems(asmtId);
        for (int i = 0; i < asmtItems.size(); i++) {
            Map item = asmtItems.get(i);
            // 获取条目具体选择项
            Long itemId = Long.valueOf(item.get("itemId").toString());
            List<Map<String, Object>> asmtItemDics = sdsToolSdkMapper.getASMTItemDics(itemId);
            String dicScore = asmtItemDics.get(0).get("dicScore").toString();
            asmtItems.get(i).put("itemDics", asmtItemDics);
            asmtItems.get(i).put("dicScore", dicScore);
        }
        SdcBusiEvaluationEntity sdcBusiEvaluationEntity = sdcBusiEvaluationMapper.selectById(evalId);

        Wrapper<SdcBusiEvaluationItemEntity> wpr = new EntityWrapper<>();
        wpr.eq("evaluation_id", params.get("evalId"));
        List<SdcBusiEvaluationItemEntity> sdcBusiEvaluationItemEntities = sdcBusiEvaluationItemMapper.selectList(wpr);

        result.put("hosp", hospitalName);
        result.put("entityName", sdsQcentityEntity.getBtDesc());
        result.put("asmtName", sdcBaseAssessmentEntity.getDescription());
        result.put("patientName", cdcEpisodeEntity.getName());
        result.put("patientGender", cdcEpisodeEntity.getGender());
        result.put("patientAge", cdcEpisodeEntity.getAge());
        result.put("patientMrNum", cdcEpisodeEntity.getMrNum());
        result.put("admLocDesc", cdcEpisodeEntity.getAdmLocDesc());
        result.put("admDate", cdcEpisodeEntity.getAdmDate());
        result.put("dishDate", cdcEpisodeEntity.getDishDate());
        result.put("asmtItems", asmtItems);
        result.put("evalUpdateDate", sdcBusiEvaluationEntity.getUpdateDate());
        if (!StringUtils.isEmpty(sdcBusiEvaluationEntity.getUpdateName())){
            result.put("evalUpdateUser", sdcBusiEvaluationEntity.getUpdateName());
        }
        result.put("selectedItems", sdcBusiEvaluationItemEntities);
        return result;
    }

    @Override
    public Object gettAutoNodeInfo(Map<String, Object> params) {
       return sdcBusiEvaluationHisMapper.selectList(new EntityWrapper<SdcBusiEvaluationHisEntity>()
               .eq("episode_id", params.get("patientId"))
               .eq("assessment_id", params.get("asmtId"))
               .eq("auto", 1)
               .eq("come_from",0));
    }

    @Override
    public String getItemKeyFrom(Map<String, Object> params) {
        String res = "";
        if (!StringUtils.isEmpty(params.get("evalItemId"))){
            String evalItemId = params.get("evalItemId").toString();
            SdcBusiEvaluationHisEntity sdcBusiEvaluationHisEntity = new SdcBusiEvaluationHisEntity();
            sdcBusiEvaluationHisEntity.setEvalItemId(Long.parseLong(evalItemId));
            sdcBusiEvaluationHisEntity = sdcBusiEvaluationHisMapper.selectOne(sdcBusiEvaluationHisEntity);
            if (!StringUtils.isEmpty(sdcBusiEvaluationHisEntity)){
                Integer auto = sdcBusiEvaluationHisEntity.getAuto();
                if (auto == 1){
                    res = sdcBusiEvaluationHisEntity.getKeyWordsfrom();
                }else {
                    String time = DateUtil.getTime(sdcBusiEvaluationHisEntity.getEvalDate());
                    res = sdcBusiEvaluationHisEntity.getKeyWordsfrom() + ":" + sdcBusiEvaluationHisEntity.getEvalDocName() + " " + time;
                }
            }
        }
        if (!StringUtils.isEmpty(params.get("evalHisId"))){
            String evalHisId = params.get("evalHisId").toString();
            SdcBusiEvaluationHisEntity sdcBusiEvaluationHisEntity = sdcBusiEvaluationHisMapper.selectById(Long.parseLong(evalHisId));
            if (!StringUtils.isEmpty(sdcBusiEvaluationHisEntity)){
                res = sdcBusiEvaluationHisEntity.getKeyWordsfrom();
            }
        }

        return res;
    }

    @Override
    public void synDiagnosData(DiagnosDataDto diagnosDataDto) {
        String episodeId = diagnosDataDto.getIDNO();
        // 查询数据中心的对应的就诊id
        Map map = new HashMap();
        map.put("xcode", episodeId);
        List<CdcEpisodeEntity> cdcEpisodes = cdcEpisodeService.list(map);
        if (cdcEpisodes.size() == 0) {
            return ;
        }
        CdcEpisodeEntity cdcEpisode = cdcEpisodes.get(0);

        List<DiagnosisDto> diagnosisList = diagnosDataDto.getDiagnosisList();
        for (DiagnosisDto diagnosisDto : diagnosisList){
            Integer diagFlag = diagnosisDto.getDiagFlag();
            if (1 == diagFlag){
                //新增修改
                CdcDiagnosisEntity cdcDiagnosisEntity = new CdcDiagnosisEntity();
                cdcDiagnosisEntity.setXcode(diagnosisDto.getDiagnosisId());
                cdcDiagnosisEntity.setEpisodeId(cdcEpisode.getId());
                CdcDataEntity diagData = cdcDataService.selectByCode("DiagData");
                cdcDiagnosisEntity.setDataId(diagData.getId());
                CdcDiagnosisEntity cdcDiagnosisEntity1 = cdcDiagnosisMapper.selectOne(cdcDiagnosisEntity);
                if (null == cdcDiagnosisEntity1){
                    CdcDictionaryEntity diagType = cdcDictionaryService.queryByTypeCodeAndCode("DiagData", "bus_diag_type", diagnosisDto.getDiagnosisType());
                    cdcDiagnosisEntity.setBusDiagTypeId(diagType.getId());
                    cdcDiagnosisEntity.setDescription(diagnosisDto.getDiagnosisName());
                    cdcDiagnosisEntity.setIcd10(diagnosisDto.getDiagnosisCode());
                    cdcDiagnosisEntity.setIsMain(diagnosisDto.getIsMainDiagnosis());
                    cdcDiagnosisEntity.setDiagDate(diagnosisDto.getRecordTime());
                    CdcDictionaryEntity diagSource = cdcDictionaryService.queryByTypeCodeAndCode("DiagData", "bus_diag_source", "C");
                    cdcDiagnosisEntity.setBusDiagSourceId(diagSource.getId());
                    cdcDiagnosisEntity.setIsActive(1);
                    cdcDiagnosisEntity.setDelFlag(false);
                    cdcDiagnosisEntity.setCreateDate(new Date());
                    cdcDiagnosisEntity.setUpdateDate(new Date());
                    cdcDiagnosisEntity.insert();
                }else {
                    CdcDictionaryEntity diagType = cdcDictionaryService.queryByTypeCodeAndCode("DiagData", "bus_diag_type", diagnosisDto.getDiagnosisType());
                    cdcDiagnosisEntity1.setBusDiagTypeId(diagType.getId());
                    cdcDiagnosisEntity1.setDescription(diagnosisDto.getDiagnosisName());
                    cdcDiagnosisEntity1.setIcd10(diagnosisDto.getDiagnosisCode());
                    cdcDiagnosisEntity1.setIsMain(diagnosisDto.getIsMainDiagnosis());
                    cdcDiagnosisEntity1.setDiagDate(diagnosisDto.getRecordTime());
                    CdcDictionaryEntity diagSource = cdcDictionaryService.queryByTypeCodeAndCode("DiagData", "bus_diag_source", "C");
                    cdcDiagnosisEntity1.setBusDiagSourceId(diagSource.getId());
                    cdcDiagnosisEntity1.setIsActive(1);
                    cdcDiagnosisEntity1.setDelFlag(false);
                    cdcDiagnosisEntity1.setUpdateDate(new Date());
                    cdcDiagnosisEntity1.updateAllColumnById();
                }
            }else if (2 == diagFlag){
                //删除
                CdcDiagnosisEntity cdcDiagnosisEntity = new CdcDiagnosisEntity();
                cdcDiagnosisEntity.setXcode(diagnosisDto.getDiagnosisId());
                cdcDiagnosisEntity.setEpisodeId(cdcEpisode.getId());
                CdcDataEntity diagData = cdcDataService.selectByCode("DiagData");
                cdcDiagnosisEntity.setDataId(diagData.getId());
                CdcDiagnosisEntity cdcDiagnosisEntity1 = cdcDiagnosisMapper.selectOne(cdcDiagnosisEntity);
                if (!StringUtils.isEmpty(cdcDiagnosisEntity1)){
                    cdcDiagnosisEntity1.deleteById();
                }
            }
        }
    }

    @Override
    public JSONArray getTreatDetailInfo(Map<String, Object> params) {
        String vteQcModule = CdcConfigCache.me().getValueByKey("SDS", "VTEQcModule");
        // 如果系统配置不进行VTE相关项目的质控，且该项目是VTE通用方案则跳过
        if (CommonUtil.notEquals(vteQcModule, "Y")) {
            params.put("isVteCommon", 1);
        }
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        // 获取病种诊疗阶段
        List<SdcCdssItemStageDicEntity> stageDicList = sdcCdssItemStageDicMapper.list(params);
        for (SdcCdssItemStageDicEntity stageDic : stageDicList) {
            params.put("stateOrder", stageDic.getStateOrder());
            params.put("stageId", stageDic.getId());
            JSONObject stageObject = new JSONObject();
            stageObject.put("schemeName", stageDic.getStageName());
            stageObject.put("schemeDetail", sdcCdssItemResultMapper.itemResult(params));
            jsonArray.add(stageObject);
        }
        /*// 检查项目完成情况
        params.put("itemType", 2);
        JSONObject examObject = new JSONObject();
        examObject.put("schemeName", "检查");
        examObject.put("schemeDetail", sdcCdssItemResultMapper.itemResult(params));
        jsonArray.add(examObject);
        // 检验项目完成情况
        params.put("itemType", 3);
        JSONObject labObject = new JSONObject();
        labObject.put("schemeName", "检验");
        labObject.put("schemeDetail", sdcCdssItemResultMapper.itemResult(params));
        jsonArray.add(labObject);
        // 治疗项目完成情况
        params.put("itemType", 4);
        JSONObject orderObject = new JSONObject();
        orderObject.put("schemeName", "治疗");
        orderObject.put("schemeDetail", sdcCdssItemResultMapper.itemResult(params));
        jsonArray.add(orderObject);
        // 护理项目完成情况
        params.put("itemType", 5);
        JSONObject nursingObject = new JSONObject();
        nursingObject.put("schemeName", "护理");
        nursingObject.put("schemeDetail", sdcCdssItemResultMapper.itemResult(params));
        jsonArray.add(nursingObject);
        // 评估项目完成情况
        params.put("itemType", 1);
        JSONObject evalObject = new JSONObject();
        evalObject.put("schemeName", "评估");
        evalObject.put("schemeDetail", sdcCdssItemResultMapper.itemResult(params));
        jsonArray.add(evalObject);*/

        return jsonArray;
    }

    private void updateBusiEvaluationHis(Long assessmenentryId, Long episodeId, boolean flag, Long evalItemId, String modifyUserName, Long asmtId){
        int auto;
        String keyWordsfrom = "";
        SdcBusiEvaluationHisEntity sdcBusiEvaluationHisEntity = new SdcBusiEvaluationHisEntity();
        sdcBusiEvaluationHisEntity.setEpisodeId(episodeId);
        sdcBusiEvaluationHisEntity.setAssessmentEntryId(assessmenentryId);
        sdcBusiEvaluationHisEntity.setAssessmentId(asmtId);
        if (flag){
            //自动
            auto = 1;
            keyWordsfrom = sdcBusiEvaluationHisMapper.selectAutoKeyWordsfrom(episodeId, assessmenentryId, asmtId);
        }else {
            //手动
            auto = 0;
            keyWordsfrom = "临床确认";
        }
        sdcBusiEvaluationHisEntity.setAuto(auto);
        sdcBusiEvaluationHisEntity.setEvalItemId(evalItemId);
        sdcBusiEvaluationHisEntity = sdcBusiEvaluationHisMapper.selectOne(sdcBusiEvaluationHisEntity);
        if (null == sdcBusiEvaluationHisEntity){
            //insert
            sdcBusiEvaluationHisEntity = new SdcBusiEvaluationHisEntity();
            sdcBusiEvaluationHisEntity.setEpisodeId(episodeId);
            sdcBusiEvaluationHisEntity.setAssessmentEntryId(assessmenentryId);
            sdcBusiEvaluationHisEntity.setResult("");
            sdcBusiEvaluationHisEntity.setEvalDate(new Date());
            sdcBusiEvaluationHisEntity.setAssessmentId(asmtId);
            sdcBusiEvaluationHisEntity.setKeyWordsfrom(keyWordsfrom);
            sdcBusiEvaluationHisEntity.setAuto(auto);
            sdcBusiEvaluationHisEntity.setEvalDocName(modifyUserName);
            sdcBusiEvaluationHisEntity.setEvalItemId(evalItemId);
            sdcBusiEvaluationHisEntity.insert();
        }else {
            //update
            sdcBusiEvaluationHisEntity.setResult("");
            sdcBusiEvaluationHisEntity.setKeyWordsfrom(keyWordsfrom);
            sdcBusiEvaluationHisEntity.setEvalDate(new Date());
            sdcBusiEvaluationHisEntity.setEvalDocName(modifyUserName);
            sdcBusiEvaluationHisEntity.updateById();
        }

    }

}